package com.hopu.springbootdemo2.filter;

import com.hopu.springbootdemo2.service.UserService;
import com.hopu.springbootdemo2.util.ApplicationContextUtils;
import com.hopu.springbootdemo2.util.JwtUtils;
import com.hopu.springbootdemo2.util.RsaUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * JWT token验证过滤器
 */
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    //过滤请求
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获得token并进行验证
        String token = request.getHeader("Authorization");
        if(token == null){
            throw new RuntimeException("token is null");
        }
        try{
            String username = JwtUtils.getUsernameFromToken(token, RsaUtils.publicKey);
            System.out.println("username-->" + username);
            //数据库授权
            UserService userService = ApplicationContextUtils.getBean(UserService.class);
            List<GrantedAuthority> authorities = userService.findAuthoritiesByUsername(username);
            //发送通行证
            UsernamePasswordAuthenticationToken uToken
                    = new UsernamePasswordAuthenticationToken(username,"",
                    authorities);
            SecurityContextHolder.getContext().setAuthentication(uToken);
        }catch (Exception ex){
            throw new RuntimeException(ex);
        }
        //放行请求
        chain.doFilter(request,response);
    }
}
